package com.visionblue.business.ship.page

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import com.visionblue.business.ship.App
import com.visionblue.business.ship.R
import com.visionblue.business.ship.base.BaseVMActivity
import com.visionblue.business.ship.base.DefaultObserver
import com.visionblue.business.ship.model.bean.response.ApplicationDetail
import com.visionblue.business.ship.model.bean.response.NotificationBean
import com.visionblue.business.ship.model.bean.response.ShipInfo
import com.visionblue.business.ship.page.collection.CollectionActivity
import com.visionblue.business.ship.page.dialog.CachedOrderDialog
import com.visionblue.business.ship.page.dialog.DevicePwdDialog
import com.visionblue.business.ship.page.dialog.NotRegistryMaskDialog
import com.visionblue.business.ship.page.dialog.TaskSlideDialog
import com.visionblue.business.ship.page.orders.OrderActivity
import com.visionblue.business.ship.page.outer.OuterActivity
import com.visionblue.business.ship.page.outer.OuterNewActivity
import com.visionblue.business.ship.service.HeartbeatService
import com.visionblue.business.ship.util.ext.setVisible
import com.visionblue.business.ship.util.toast
import kotlinx.android.synthetic.main.activity_main.*
import org.koin.androidx.viewmodel.ext.android.getViewModel

class MainActivity : BaseVMActivity<MainViewModel>() {
    private var  myApplications: List<ApplicationDetail>?=null
    private var mShipName: String? = null
    private val mSlideDialog: TaskSlideDialog by lazy {
        TaskSlideDialog(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        ivMsg.setOnClickListener {
//            try {
//                val list = mutableListOf<String>()
//                repeat(7) {
//                    list.add("含油污水：98.98m^3")
//                }
//                PrintService.start(
//                    this, PrintInfo(
//                        "浙商001",
//                        "众合1",
//                        "2020-05-02",
//                        list,
//                        "https://www.baidu.com/"
//                    )
//                )
//            } catch (e: Exception) {
//                MLog.e(e.message.toString())
//            }
            mViewModel.getApplications()
//            CollectionActivity.start(
//                this@MainActivity,
//                applicationDetail = ApplicationDetail(
//                    id = "999",
//                    shipName = "hello",
//                    shipInfo = ShipInfo(
//                        shipName = "hello",
//                        shipNo = null,
//                        shipModel = null,
//                        shipType = null,
//                        mobile = null,
//                        isConflicting = false
//                    )
//                    ,
//                    recordNo = null,
//                    status = 1,
//                    readStatus = 1,
//                    pdfUrl = null,
//                    wasteInfos = emptyMap(),
//                    workTime = -1L,
//                    createTime = -1L,
//                    address = null,
//                    poiName = null,
//                    latitude = null,
//                    longitude = null
//                )
//            )
        }

        btnIn.setOnClickListener {
            CollectionActivity.start(it.context,"主页按钮")
        }

        iv_orders.setOnClickListener {
            //startActivity(Intent(this, PrintInitActivity::class.java))
            //CrashReport.testJavaCrash()//测试bugly异常上报
            OrderActivity.start(this,mShipName.toString())
        }


        tvShipName.setOnClickListener {
            DevicePwdDialog(this).show()
        }

        btnOut.setOnClickListener {
            //5.20新需求
            OuterNewActivity.start(this)
            //OuterActivity.start(this)
        }

        btnCache.setOnClickListener {
            val cachedOrders = mViewModel.cachedOrderLiveData.value
//            if (cachedOrders != null && cachedOrders.isNotEmpty()) {
            CachedOrderDialog(this, cachedOrders).show()
//            }
        }
    }

    override fun initVM(): MainViewModel = getViewModel()

    override fun initData() {
        super.initData()

        mViewModel.hostShipInfoState.observe(this, DefaultObserver(action = {
            onShipInfoGot(it.data)
        }))

        mViewModel.notificationState.observe(this, DefaultObserver {
            val data = it.data
            if (data != null) {
                onNotificationGot(data)
            }
        })


        mViewModel.applicationsState.observe(
            this, DefaultObserver(finallyAction = {
                ivMsg.isEnabled = true
            }, errorAction = {
                mSlideDialog.showError()
            }, loadingAction = {
                ivMsg.isEnabled = false
                mSlideDialog.showLoading()
            }, action = {
                val data = it.data
                if (data != null) {
                    onApplicationsGot(
                        it.data.hasNext(),
                        it.data.hasPre(), data.content
                    )
                }
            })
        )

        // 拒绝/接收污染物结果响应
        mViewModel.operateTaskEvent.observe(this, DefaultObserver(finallyAction = {
            mDialog.dismiss()
        }, loadingAction = {
            mDialog.show()
        }, action = {
            toast { "操作成功" }
            mViewModel.getApplicationsAfterOperation()
        }))

        mViewModel.cachedOrderLiveData.observe(this, Observer {
            if (it.isEmpty()) {
                tvOrderCount.visibility = View.GONE
            } else {
                tvOrderCount.visibility = View.VISIBLE
            }

            tvOrderCount.text = "${if (it.size > 99) "99+" else it.size}"
        })

    }


    private fun onApplicationsGot(
        hasNext: Boolean,
        hasPre: Boolean,
        applications: List<ApplicationDetail>
    ) {
        if (applications.isNotEmpty()) {
            if (!applications[0].isRead()) {
                mViewModel.setApplicationRead(applications[0].id)
            }
            mSlideDialog.showContent(
                applications[0],
                hasNext,
                hasPre,
                object : TaskSlideDialog.OnViewsClickListener {
                    override fun onStartCollectClick(detail: ApplicationDetail) {
                        CollectionActivity.start(this@MainActivity,"弹框", applicationDetail = detail)
                    }

                    override fun onDeclineClick(id: String?) {
                        mViewModel.declineTask(id)
                    }

                    override fun onSureReceiveClick(id: String?, detail: ApplicationDetail) {
                        AlertDialog.Builder(this@MainActivity)
                            .setMessage(R.string.sure_to_collect_this_task)
                            .setPositiveButton(R.string.yes) { dialog, _ ->
                                dialog.dismiss()
                                // 确认接收任务单
                                mViewModel.receiveTask(id)
                            }
                            .setNegativeButton(R.string.no) { dialog, _ ->
                                dialog.dismiss()
                            }
                            .show()
                    }

                    override fun onPreClick() {
                        mViewModel.prePage()
                    }

                    override fun onNextClick() {
                        mViewModel.nextPage()
                    }

                    override fun onDismiss() {
                        // 每次从第一页开始显示
                        mViewModel.resetPageNum()
                    }

                    override fun onClose() {

                    }
                })
        } else {
            mSlideDialog.showEmpty()
        }
    }

    override fun onResume() {
        super.onResume()
        if (mViewModel.isDeviceRegistry()) {
            mViewModel.loadDataScheduled()
            mViewModel.loadCachedOrderInfo()
        } else {
            showNotRegistryMaskView()
        }

        HeartbeatService.start(App.context)
    }

    private fun showNotRegistryMaskView() {
        val dialog =
            NotRegistryMaskDialog(this)
        dialog.setCancelable(false)
        dialog.show()
    }

    override fun onPause() {
        super.onPause()
        mViewModel.cancelSchedule()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                CODE_REGISTER -> {
                    mSlideDialog.clear()
                    mViewModel.refreshHostShipInfo()
                }
            }
        }
    }

    private fun onShipInfoGot(data: ShipInfo?) {
        mShipName = data?.shipName
        tvShipName.text = data?.shipName ?: "--"
        mViewModel.cacheDeviceInfo(data?.shipName)
    }

    private fun onNotificationGot(notificationBean: NotificationBean) {
        tvMsg.setVisible(notificationBean.pending > 0)
        tvMsg.text =
            if (notificationBean.isMoreHundred()) "99+" else notificationBean.pending.toString()

//        if (notificationBean.processing > 0) {
//            tvNewTask.setVisible(true)
//            tvTaskIn.setVisible(true)
//            tvNewTask.text =
//                StringUtils.getString(
//                    R.string.new_task_amount_format,
//                    notificationBean.pending.toString()
//                )
//            tvTaskIn.text =
//                StringUtils.getString(
//                    R.string.receiving_amount_format,
//                    notificationBean.processing.toString()
//                )
//        } else {
        tvNewTask.visibility = View.INVISIBLE
        tvTaskIn.visibility = View.INVISIBLE
//        }
    }

    companion object {
        const val CODE_REGISTER = 200
    }
}
